import { useEffect, useRef } from "react";
import * as echarts from "echarts";
import classNames from "classnames";

interface Props {
  className?: string;
  title?: string;
  data: Array<unknown>;
}

export default function LineChart<Props>(props: Props) {
  const { title, data } = props;
  const domRef = useRef(null);

  const parseData = (list: Array<unknown>) => {
    const xAxisData = [];
    const yAxisData = [];
    list.forEach((item) => {
      xAxisData.push(item.label);
      yAxisData.push(item.value);
    });

    return {
      xAxisData,
      yAxisData,
    };
  };

  const initChart = () => {
    const chart = echarts.init(domRef.current, "purple");

    const { xAxisData, yAxisData } = parseData(data);
    chart.setOption({
      title: {
        text: title,
        textStyle: {
          fontSize: 16
        }
      },
      grid: {
        top: "40px",
        right: "20px",
        bottom: "26px",
        left: "46px",
      },
      xAxis: {
        type: "category",
        data: xAxisData,
        splitArea: {
          show: true,
          areaStyle: {
            color: ["rgba(5,5,15,0.2)", "rgba(250,250,250,0)"],
          },
        },
        axisTick: {
          show: true,
        },
      },
      yAxis: {
        type: "value",
        splitArea: {
          show: true,
          areaStyle: {
            color: ["rgba(5,5,15,0.2)", "rgba(250,250,250,0)"],
          },
        },

        axisLine: {
          show: true,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      series: [
        {
          data: yAxisData,
          type: "line",
          showSymbol: false,
          smooth: true,
        },
      ],
    });
    window.addEventListener("resize", function () {
      chart.resize();
    });
  };

  const className = classNames("size-full", props.className);

  useEffect(() => {
    initChart();
  }, []);

  return <div ref={domRef} className={className}></div>;
}
